using AutoMapper;
using BaseData.WriteApi.Appcontext.Command.Sheep_Records;
using MediatR;
using SmartTracking.Domain.HQX;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;

namespace BaseData.WriteApi.Appcontext.CommandHandler.Sheep_Records
{
    /// <summary>
    /// 羊只档案更新命令处理器
    /// </summary>
    public class UpdateSheepRecordCommandHandler : IRequestHandler<UpdateSheepRecordCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<SheepRecords> _sheepRecordRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<UpdateSheepRecordCommandHandler> _logger;

        public UpdateSheepRecordCommandHandler(
            IBaseRepository<SheepRecords> sheepRecordRepository,
            IMapper mapper,
            ILogger<UpdateSheepRecordCommandHandler> logger)
        {
            _sheepRecordRepository = sheepRecordRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理羊只档案更新命令
        /// </summary>
        /// <param name="request">羊只档案更新命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>更新结果</returns>
        public async Task<ApiResult<bool>> Handle(UpdateSheepRecordCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证请求参数
                if (request == null)
                {
                    _logger.LogWarning("羊只档案更新请求参数为空");
                    return new ApiResult<bool> { Code = ApiEnum.更新失败, Message = "请求参数不能为空", data = false };
                }

                // 验证数据
                if (!request.Validate(out string errorMessage))
                {
                    _logger.LogWarning($"羊只档案更新数据验证失败: {errorMessage}");
                    return new ApiResult<bool> { Code = ApiEnum.更新失败, Message = errorMessage, data = false };
                }

                // 根据ID查询羊只档案
                var sheepRecord = await _sheepRecordRepository.GetByIdAsync(request.SheepId);
                
                if (sheepRecord == null)
                {
                    _logger.LogWarning($"未找到ID为 {request.SheepId} 的羊只档案");
                    return new ApiResult<bool> { Code = ApiEnum.查询失败, Message = "未找到指定的羊只档案", data = false };
                }

                // 检查是否已被删除
                if (sheepRecord.IsDeleted)
                {
                    _logger.LogWarning($"ID为 {request.SheepId} 的羊只档案已被删除");
                    return new ApiResult<bool> { Code = ApiEnum.查询失败, Message = "羊只档案已被删除", data = false };
                }

                // 更新羊只档案信息
                sheepRecord.VisibleNumber = request.VisibleNumber;
                sheepRecord.ElectronNumber = request.ElectronNumber;
                sheepRecord.Variety = request.Variety;
                sheepRecord.Gender = request.Gender;
                sheepRecord.DateofBirth = request.DateofBirth;
                sheepRecord.Ageinmonths = request.Ageinmonths;
                sheepRecord.Growthstage = request.Growthstage;
                sheepRecord.Building = request.Building;
                sheepRecord.Column = request.Column;
                sheepRecord.TypeofSheep = request.TypeofSheep;
                sheepRecord.GeneRank = request.GeneRank;
                sheepRecord.ProductionGrade = request.ProductionGrade;
                sheepRecord.SalesLevel = request.SalesLevel;
                sheepRecord.Reproductivestatus = request.Reproductivestatus;
                sheepRecord.PrenatalCheckup = request.PrenatalCheckup;
                sheepRecord.ReproductiveStatusDay = request.ReproductiveStatusDay;
                sheepRecord.BirthWeight = request.BirthWeight;
                sheepRecord.WeaningWeight = request.WeaningWeight;
                sheepRecord.WeaningDate = request.WeaningDate;
                sheepRecord.WeaningAge = request.WeaningAge;
                sheepRecord.FatherNumber = request.FatherNumber;
                sheepRecord.MotherNumber = request.MotherNumber;
                sheepRecord.PresenceStatus = request.PresenceStatus;
                sheepRecord.Note = request.Note;
                
                // 执行更新
                var result = await _sheepRecordRepository.UpdateAsync(sheepRecord);
                
                if (result>0)
                {
                    _logger.LogInformation($"成功更新羊只档案，ID: {request.SheepId}");
                    return new ApiResult<bool> { Code = ApiEnum.更新成功, Message = "羊只档案更新成功", data = true };
                }
                else
                {
                    _logger.LogError($"更新羊只档案失败，ID: {request.SheepId}");
                    return new ApiResult<bool> { Code = ApiEnum.更新失败, Message = "羊只档案更新失败", data = false };
                }
            }
            catch (ArgumentException ex)
            {
                _logger.LogWarning($"参数验证异常: {ex.Message}");
                return new ApiResult<bool> { Code = ApiEnum.更新失败, Message = ex.Message, data = false };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新羊只档案时发生系统异常: {ex.Message}");
                return new ApiResult<bool> { Code = ApiEnum.更新失败, Message = "系统异常，请联系管理员", data = false };
            }
        }
    }
}